package com.striver.registry.config.consul;

import com.ecwid.consul.v1.ConsulClient;
import com.striver.registry.properties.StriverRegistyProperties;
import org.apache.commons.lang.StringUtils;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.consul.ConditionalOnConsulEnabled;
import org.springframework.cloud.consul.ConsulProperties;
import org.springframework.cloud.consul.discovery.ConsulDiscoveryProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

@Configuration
@ConditionalOnConsulEnabled
@EnableConfigurationProperties(StriverRegistyProperties.class)
public class ConsulRegistryConfig {

    @Bean
    public ConsulClient consulClient(StriverRegistyProperties registryProperties, ConsulDiscoveryProperties consulDiscoveryProperties) {
        int agentPort = registryProperties.getPort();
        String agentHost = !StringUtils.isEmpty(registryProperties.getScheme()) ? registryProperties.getScheme() + "://" + registryProperties.getHost() : registryProperties.getHost();
        consulDiscoveryProperties.setPreferIpAddress(registryProperties.isPreferIpAddress());
        consulDiscoveryProperties.setScheme(registryProperties.getScheme());
        consulDiscoveryProperties.setHealthCheckInterval(registryProperties.getHealthCheckInterval());
        consulDiscoveryProperties.setEnabled(registryProperties.getType().equals(StriverRegistyProperties.Type.consul));
        if (StringUtils.isNotBlank(registryProperties.getHealthCheckPath())) {
            consulDiscoveryProperties.setHealthCheckPath(registryProperties.getHealthCheckPath());
        }

        if (StringUtils.isNotBlank(registryProperties.getInstanceId())) {
            consulDiscoveryProperties.setInstanceId(registryProperties.getInstanceId());
        }

        if (StringUtils.isNotBlank(registryProperties.getIpAddress())) {
            consulDiscoveryProperties.setIpAddress(registryProperties.getIpAddress());
        }

        List<String> tags = new ArrayList();
        tags.add("registerTime=" + System.currentTimeMillis());
        if (registryProperties.getTags() != null) {
            tags.addAll(registryProperties.getTags());
        }

        consulDiscoveryProperties.setTags(tags);
        if (registryProperties.getTls() != null) {
            ConsulProperties.TLSConfig tls = registryProperties.getTls();
            com.ecwid.consul.transport.TLSConfig tlsConfig = new com.ecwid.consul.transport.TLSConfig(tls.getKeyStoreInstanceType(), tls.getCertificatePath(), tls.getCertificatePassword(), tls.getKeyStorePath(), tls.getKeyStorePassword());
            return new ConsulClient(agentHost, agentPort, tlsConfig);
        } else {
            return new ConsulClient(agentHost, agentPort);
        }
    }
}
